<template>
	<view class="container">
		<view v-if="list.length" class="cart-list">
			<view class="cart-item" v-for="(item, index) in list" :key="index">
				<label class="item-radio" @click.stop="handleCheckItem(item.id)">
					<radio class="radio" color="#000" :checked="inArray(item.id, checkedIds)" />
				</label>
				<view class="goods-image">
					<u--image :src="item.cover" width="200rpx" height="200rpx" mode="scaleToFill">
					</u--image>
				</view>
				<view class="item-content">
					<view class="goods-title">
						<text class="twoline-hide">{{ item.title }}</text>
						<view class="" @click="fillDelete(item)">
							<u-icon name="trash"></u-icon>
						</view>
					</view>
					<view class="goods-props clearfix">
						<view class="goods-props-item">
							<text>{{ item.description }}</text>
						</view>
					</view>
					<view class="item-foot">
						<view class="goods-price">
							<text class="unit">￥</text>
							<text class="value">{{ item.price }}</text>
						</view>
						<view class="stepper"> </view>
					</view>
				</view>
			</view>
		</view>

		<u-empty v-if="!list.length" mode="car" icon="http://cdn.uviewui.com/uview/empty/car.png"
			:custom-style="{ padding: '100rpx 50rpx 180rpx', background: '#fff' }" tips="您的购物车是空的, 快去逛逛吧">
		</u-empty>

		<!-- 底部操作栏 -->
		<view v-if="list.length" class="footer-fixed">
			<label class="all-radio" @click="handleCheckAll">
				<radio class="radio" color="#000"
					:checked="checkedIds.length > 0 && checkedIds.length === list.length" />
				<text>全选</text>
			</label>
			<view class="total-info">
				<text>总价：</text>
				<view class="goods-price">
					<text class="unit">￥</text>
					<text class="value">{{ totalPrice }}</text>
				</view>
			</view>
			<view class="cart-action">
				<view class="btn-wrapper">
					<view class="btn-item btn-main" @click="handleOrder">
						<text>去结算 </text>
					</view>
				</view>
			</view>
		</view>

	<!-- 	<u-popup :show="show" @close="close" @open="open">
			<view class="close-wx" @click="wxpay">
				<text class="iconfont icon-weixin" style="color: #1ca436"></text>微信支付
			</view>
		</u-popup> -->

		<PageNavBar :tabIndex="2" />
	</view>
</template>

<script>
	import {
		inArray,
		arrayIntersect,
		isWeixin
	} from "@/utils/util";
	import PageNavBar from "@/components/nav_footer/index.vue";
	import config from '@/utils/config'
	import {
		api_getshopcart,
		api_removeshop,
		api_getweixinopenid
	} from "@/api/cart";
	const CartIdsIndex = "CartIds";
	export default {
		components: {
			PageNavBar,
		},
		data() {
			return {
				afterRead: "",
				show: false,
				title: "Hello",
				list: [],
				// 选中列表
				checkedIds: [],
				inArray,

				// 选中的商品总金额
				totalPrice: "0.00",

				fileList: [{
						url: "https://img01.yzcdn.cn/vant/leaf.jpg",
					},
					// Uploader 根据文件后缀来判断是否为图片文件
					// 如果图片 URL 中不包含类型信息，可以添加 isImage 标记来声明
					{
						url: "https://cloud-image",
						isImage: true,
					},
				],
			};
		},
		watch: {
			// 监听选中的商品
			checkedIds: {
				handler(val) {
					// 计算合计金额
					this.onCalcTotalPrice();
					// 记录到缓存中
					uni.setStorageSync(CartIdsIndex, val);
				},
				immediate: false,
			},
			// 监听购物车商品总数量
			total(val) {},
		},
		onLoad() {
			this.getCartList();
		},
		methods: {
			// 选中商品
			handleCheckItem(cartId) {
				const {
					checkedIds
				} = this;
				const index = checkedIds.findIndex((id) => id === cartId);
				index < 0 ? checkedIds.push(cartId) : checkedIds.splice(index, 1);
			},

			// 全选
			handleCheckAll() {
				const {
					checkedIds,
					list
				} = this;
				this.checkedIds =
					checkedIds.length === list.length ? [] : list.map((item) => item.id);
			},
			// 计算合计金额 (根据选中的商品)
			onCalcTotalPrice() {
				const app = this;
				// 选中的商品记录
				const checkedList = app.list.filter((item) =>
					inArray(item.id, app.checkedIds)
				);
				// 计算总金额
				let tempPrice = 0;
				checkedList.forEach((item) => {
					// 商品单价, 为了方便计算先转换单位为分 (整数)
					const unitPrice = item.price * 100;
					tempPrice += unitPrice * item.num;
				});
				app.totalPrice = (tempPrice / 100).toFixed(2);
			},

			// 结算选中的商品
			handleOrder() {
				const app = this;

				if (app.checkedIds.length) {
					const cartIds = app.checkedIds.join();
					uni.navigateTo({
						url: `/pages/placeorder/index?ids=${cartIds}&scene=cart`,
					});
					// app.show = true;
				}
			},
			fillDelete(item) {
				let app = this;
				uni.showModal({
					title: "友情提示",
					content: "您确定要删除该商品吗？",
					showCancel: true,
					async success({
						confirm
					}) {
						if (confirm) {
							let res = await api_removeshop({
								id: item.id,
								shop_name: "db"
							});
							// console.log(res)
							if (res.code == 1) {
								app.getCartList();
								app.onClearInvalidId();
							}

							// console.log(item,"item")
							// 确认删除
							// app.getCartList();
							// app.onClearInvalidId()
						}
					},
				});
			},
			// 获取购物车商品列表
			async getCartList() {
				const app = this;
				uni.showLoading({
					title: "数据加载中..."
				});

				let res = await api_getshopcart({
					shop_name: "db",
				});
				uni.hideLoading();

				if (res.code == 1) {
					app.list = res.data.list;
					app.onClearInvalidId();
				}

				// console.log(res)

				// app.onClearInvalidId()
				// app.isLoading = true
				// CartApi.list()
				//   .then(result => {
				//     app.list = result.data.list
				//     app.total = result.data.cartTotal
				//     // 清除checkedIds中无效的ID
				//     app.onClearInvalidId()
				//   })
				//   .finally(() => app.isLoading = false)
			},
			// 清除checkedIds中无效的ID
			onClearInvalidId() {
				const app = this;
				const listIds = app.list.map((item) => item.id);
				app.checkedIds = arrayIntersect(listIds, app.checkedIds);
			},
			async wxpay() {


				console.log(this.checkedIds, "this.checkedIds")
				var arr = [];
				for (let i = 0; i < this.checkedIds.length; i++) {
					let curIndex = this.list.findIndex(item => {
						return item.id == this.checkedIds[i]
					})

					let params = {
						columnid: this.list[curIndex].columnid,
						knowledgeid: this.list[curIndex].knowledgeid,
						title: this.list[curIndex].title,
						cover: this.list[curIndex].cover,
						description: this.list[curIndex].description,
						price: this.list[curIndex].price,
						totalprice: this.totalPrice
					};
					arr.push(params);
				}


				let FrontUrl = window.location.protocol + '//' + window.location.host;
				const nexturl = FrontUrl +
					`/pages/cart/index?shopinfo=${encodeURIComponent(JSON.stringify(arr))}`; //跳转到下一个页面的地址http://192.168.2.11/#/xuejing/order/test1?id=8

				let url = config.baseURL + '/user/wxzhifu/getweixinopenid' +
					`?nexturl=${encodeURIComponent(nexturl)}`; //请求获得openid并存入到服务器的Cache当中
				window.location.href = url;

				// window.location.href = nexturl;
			},
			open() {
				// console.log('open');
			},
			close() {
				this.show = false;
				// console.log('close');
			},
		},
	};
</script>

<style lang="scss" scoped>
	.my_wrapper {
		background-color: #eee;
	}

	.container {
		// min-height: 90vh;
		// background: #EEEEEE;
	}

	.cate-container {
		// background: #EEEEEE;
	}

	// 购物车列表
	.cart-list {
		padding: 40rpx 16rpx 240rpx 16rpx;
	}

	.cart-item {
		background: #fff;
		box-shadow: 0 1px 10px rgba(0, 0, 0, 0.2);
		border-radius: 12rpx;
		display: flex;
		align-items: center;
		padding: 30rpx 16rpx;
		margin-bottom: 24rpx;

		.item-radio {
			width: 56rpx;
			height: 80rpx;
			line-height: 80rpx;
			border-radius: 3px;
			margin-right: 10rpx;
			text-align: center;

			::v-deep .radio {
				transform: scale(0.76);

				.uni-radio-input {
					width: 46rpx;
					height: 46rpx;
					// border-radius: 3px;
				}
			}
		}

		.goods-image {
			width: 200rpx;
			height: 200rpx;
			border-radius: 10rpx;
			overflow: hidden;

			.image {
				display: block;
				width: 100%;
				height: 100%;
				border-radius: 8rpx;
			}
		}

		.item-content {
			flex: 1;
			padding-left: 24rpx;

			.goods-title {
				display: flex;
				justify-content: space-between;
				font-size: 28rpx;
				max-height: 76rpx;

				.twoline-hide {
					font-weight: bold;
				}
			}

			.goods-props {
				margin-top: 14rpx;
				height: 40rpx;
				color: #ababab;
				font-size: 24rpx;
				overflow: hidden;

				.goods-props-item {
					display: inline-block;
					margin-right: 14rpx;
					padding: 4rpx 16rpx;
					border-radius: 12rpx;
					background-color: #f5f5f5;
					width: auto;
				}
			}

			.item-foot {
				display: flex;
				justify-content: space-between;
				align-items: center;
				margin-top: 20rpx;

				.goods-price {
					vertical-align: bottom;
					// color: $uni-text-color-active;
					color: #c91623;

					.unit {
						font-size: 24rpx;
					}

					.value {
						font-size: 32rpx;
					}
				}
			}
		}
	}

	// 空数据按钮
	.empty-ipt {
		width: 220rpx;
		margin: 0 auto;
		font-size: 32rpx;
		height: 80rpx;
		line-height: 80rpx;
		text-align: center;
		color: #fff;
		// border-radius: 50rpx;
		// background: linear-gradient(to right, #f9211c, #ff6335);
		background-color: #000;
	}

	// 底部操作栏
	.footer-fixed {
		display: flex;
		align-items: center;
		height: 96rpx;
		background: #fff;
		// padding: 0 30rpx;
		padding: 0 0 0 30rpx;
		position: fixed;
		// bottom: var(--window-bottom);
		bottom: 50px;
		left: 0;
		right: 0;
		z-index: 11;

		.all-radio {
			width: 140rpx;
			display: flex;
			align-items: center;

			::v-deep .radio {
				margin-bottom: -4rpx;
				transform: scale(0.76);

				.uni-radio-input {
					width: 46rpx;
					height: 46rpx;
					// border-radius: 3px;
				}
			}
		}

		.total-info {
			flex: 1;
			display: flex;
			align-items: center;
			justify-content: flex-end;
			padding-right: 30rpx;

			.goods-price {
				vertical-align: bottom;
				// color: #fa2209;
				color: #000;

				.unit {
					font-size: 24rpx;
				}

				.value {
					font-size: 32rpx;
				}
			}
		}

		.cart-action {
			width: 200rpx;

			.btn-wrapper {
				height: 100%;
				display: flex;
				align-items: center;
			}

			.btn-item {
				flex: 1;
				font-size: 28rpx;
				height: 96rpx;
				line-height: 96rpx;
				text-align: center;
				color: #fff;
				// border-radius: 50rpx;
			}

			// 立即购买按钮
			.btn-main {
				// background: linear-gradient(to right, #f9211c, #ff6335);
				background-color: #000;

				// 禁用按钮
				&.disabled {
					background-color: #ccc;
				}
			}
		}
	}

	.close-wx {
		height: 100rpx;
		display: flex;
		align-items: center;
		align-content: center;
		align-self: center;
	}
</style>